/*
 * Copyright (c) 2013-2015 SimaStudio. All rights reserved.
 *
 * This software is the confidential and proprietary information of SimaStudio.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with SimaStudio.
 *
 * SimaStudio MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * SimaStudio SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package com.asiainfo.integration.controller;

import com.asiainfo.integration.bean.CommonJsonResult;
import com.asiainfo.integration.bean.JsonResult;
import com.asiainfo.integration.quartz.ScheduleJob;
import com.asiainfo.integration.quartz.ScheduleJobService;
import com.asiainfo.integration.utils.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Usage: 任务执行
 *
 * @author Charkey
 * @date 2015/5/23 22:12
 */
@Controller
@RequestMapping("/task")
public class ScheduleJobController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleJobController.class);

    @Autowired
    private ScheduleJobService scheduleJobService;

    @RequestMapping("/taskList")
    public String taskList(Model model) {
        List<ScheduleJob> taskList = scheduleJobService.getAllTask();
        model.addAttribute("taskList", taskList);
        return "/task/taskList.jsp";
    }

    @RequestMapping("/add")
    @ResponseBody
    public JsonResult taskList(HttpServletRequest request, ScheduleJob scheduleJob) {
        CommonJsonResult jsonResult = new CommonJsonResult();
        try {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("cron表达式有误，不能被解析！");
            return jsonResult;
        }
        Object obj = null;
        try {
            if (StringUtils.isNotBlank(scheduleJob.getBeanName())) {
                obj = SpringUtils.getBean(scheduleJob.getBeanName());
            } else {
                Class clazz = Class.forName(scheduleJob.getBeanClass());
                obj = clazz.newInstance();
            }
        } catch (Exception e) {
            // do nothing.........
        }
        if (obj == null) {
            jsonResult.setMessage("未找到目标类！");
            return jsonResult;
        } else {
            Class clazz = obj.getClass();
            Method method = null;
            try {
                method = clazz.getMethod(scheduleJob.getMethodName(), null);
            } catch (Exception e) {
                // do nothing.....
            }
            if (method == null) {
                jsonResult.setMessage("未找到目标方法！");
                return jsonResult;
            }
        }
        try {
            scheduleJobService.addTask(scheduleJob);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMessage("保存失败，检查 name group 组合是否有重复！");
            return jsonResult;
        }

        jsonResult.setSuccess(true);
        return jsonResult;
    }

    @RequestMapping("/changeJobStatus")
    @ResponseBody
    public JsonResult changeJobStatus(Integer id, String cmd) {
        CommonJsonResult jsonResult = new CommonJsonResult();
        try {
            scheduleJobService.changeStatus(id, cmd);
        } catch (SchedulerException e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(e.getMessage(), e);
            }
            jsonResult.setSuccess(false);
            jsonResult.setMessage("任务状态改变失败！");
            return jsonResult;
        }
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    @RequestMapping("/updateCron")
    @ResponseBody
    public JsonResult updateCron(Integer id, String cron) {
        CommonJsonResult jsonResult = new CommonJsonResult();
        try {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("cron表达式有误，不能被解析！");
            return jsonResult;
        }
        try {
            scheduleJobService.updateCron(id, cron);
        } catch (SchedulerException e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("cron更新失败！");
            return jsonResult;
        }
        jsonResult.setSuccess(true);
        return jsonResult;
    }
}
